package com.vvvtimes.demo.service;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSONObject;
import com.vvvtimes.demo.common.dto.RestResponse;
import com.vvvtimes.demo.domain.dto.WeatherCityDTO;
import com.vvvtimes.demo.domain.mybatis.City;
import com.vvvtimes.demo.domain.vo.WeatherVo;
import com.vvvtimes.demo.mapper.CityMapper;
import com.vvvtimes.demo.util.OkHttp3ClientManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Slf4j
@Service
public class WeatherService {

    @Resource
    private CityMapper cityMapper;


    /**
     * 获取数据
     * @param id
     * @return
     */
    @Cacheable(cacheNames = "weather_cache", key = "#id")// 从缓存获取，key为ID，缓存具体看 ehcache.xml 配置文件
    public RestResponse<WeatherVo> loadApi(String id) {
        RestResponse<WeatherVo> result =new RestResponse<>();
        String url = "http://t.weather.sojson.com/api/weather/city/"+id;
        try {
            WeatherVo weatherVo = OkHttp3ClientManager.getInstance().sendGetObject(url, WeatherVo.class);
            if(weatherVo!=null && weatherVo.isSuccess()){
                result.setResult(weatherVo);
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        return result;
    }

    public RestResponse<List<City>> queryWeatherCity(WeatherCityDTO weatherCityDTO) {
        RestResponse<List<City>> result = new RestResponse<>();
        String cityName = weatherCityDTO.getCityName();
        Example example = new Example(City.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("cityName","%"+ cityName+"%");
        List<City> cities = cityMapper.selectByExample(example);
        result.setResult(cities);
        return result;
    }

    public RestResponse<Integer> initJsonToDb() {
        RestResponse<Integer> result = new RestResponse<>();
        String filePath = WeatherService.class.getClassLoader().getResource("citycode-2019-08-23.json").getPath();
        String content = FileUtil.readUtf8String(filePath);
        List<City> cities = JSONObject.parseArray(content, City.class);
        int i = cityMapper.insertList(cities);
        result.setResult(i);
        return result;
    }
}
